package marchsoft.modules.security.service;

import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import marchsoft.enums.ResultEnum;
import marchsoft.exception.BadRequestException;
import marchsoft.modules.four.h5.entity.dto.EStudentDTO;
import marchsoft.modules.four.common.mapper.EStudentMapper;
import marchsoft.modules.security.config.bean.LoginProperties;
import marchsoft.modules.security.entity.dto.JwtFrontUserDTO;
import marchsoft.utils.RedisUtils;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.SerializationUtils;

/**
 * @ClassName FrontUserDetailsServiceImpl
 * @Author ZhuGuangLiang <786945363@qq.com>
 * @Date 2021/11/26 00:29
 */
@RequiredArgsConstructor
@Component("frontUserDetail")
public class FrontUserDetailsServiceImpl implements UserDetailsService {

	private final LoginProperties loginProperties;

	private final RedisUtils redisUtils;

	private final EStudentMapper eStudentMapper;

	@Override
	public JwtFrontUserDTO loadUserByUsername(String username) throws UsernameNotFoundException {
		boolean searchDb = true;
		JwtFrontUserDTO jwtFrontUserDTO = null;
		if (loginProperties.isCacheEnable() && redisUtils.hasKey("front::userId::" + username)) {
			jwtFrontUserDTO = (JwtFrontUserDTO) SerializationUtils.deserialize((byte[]) redisUtils.get("front::userId::" + username));
			searchDb = false;
		}
		if (searchDb) {
			EStudentDTO studentDTO= eStudentMapper.selectStudentById(username);
			if (ObjectUtil.isNull(studentDTO)) {
				throw new BadRequestException(ResultEnum.USER_NOT_EXIST);
			} else {
				jwtFrontUserDTO = new JwtFrontUserDTO(studentDTO);
				redisUtils.set("front::userId::" + username, SerializationUtils.serialize(jwtFrontUserDTO));
			}
		}
		return jwtFrontUserDTO;
	}
}
